package xyz.hubery.stream;

import com.alibaba.fastjson.JSON;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.tio.core.Tio;
import org.tio.websocket.starter.TioWebSocketServerBootstrap;
import xyz.hubery.model.MessagePayload;
import xyz.hubery.vo.ResponseEntity;

@Slf4j
@Service
public class StreamMessageListener {

    @Autowired
    private TioWebSocketServerBootstrap tioWebSocketServerBootstrap;

    /**
     * 监听消息队列中的消息，并实时推送到前端（通过WebScoket）
     * @param message
     */
    @StreamListener("tio-group")
    public void tioGroupChannel(MessagePayload message) {
        log.info("接收到 rocketmq 的消息========>{}", message);
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setSubbed(message.getChannel());
        responseEntity.put("result", message.getBody());
        // 推送给前端的用户就可以了
        if (StringUtils.hasText(message.getUserId())) {
            Tio.sendToUser(tioWebSocketServerBootstrap.getServerTioConfig(),
                    message.getUserId(), responseEntity.build());
            return;
        }
        String group = message.getChannel();
        Tio.sendToGroup(tioWebSocketServerBootstrap.getServerTioConfig(), group,
                responseEntity.build());
    }
}

